package com.example.demoback.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.log.Log;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demoback.common.Constants;
import com.example.demoback.common.Result;
import com.example.demoback.entity.License;
import com.example.demoback.exception.ServiceException;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.example.demoback.service.IPenaltyService;
import com.example.demoback.entity.Penalty;
import com.example.demoback.entity.Penalty1;
import com.example.demoback.service.IPenalty1Service;

import org.springframework.web.multipart.MultipartFile;


import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yyd
 * @since 2022-07-01
 */
@RestController
@RequestMapping("/penalty")
public class PenaltyController {

    //引入Service
    @Resource
    private IPenaltyService penaltyService;

    @Resource
    private IPenalty1Service penalty1Service;

    //新增或更新
    @PostMapping("/save")
    public Result save(@RequestBody Penalty penalty) {

        Boolean flag = false;
        //判断数据是否重复
            flag = penaltyService.saveOrUpdate(penalty);
            if (flag){
                Penalty1 penalty1 =new Penalty1();
                BeanUtil.copyProperties(penalty,penalty1,true);
                if (!penalty1Service.saveOrUpdate(penalty1)){
                return Result.error1(false);
                }
            }
        else{
                return Result.error(false,"存在重复数据");
        }
        return Result.success(flag);
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody Penalty penalty) {

        Boolean flag = false;
        //判断数据是否重复
        int a ;
        a = getInfo(penalty.getPenaltyids());
        if (a == 1) {
            flag = penaltyService.saveOrUpdate(penalty);
            if (flag) {
                Penalty1 penalty1 = new Penalty1();
                BeanUtil.copyProperties(penalty, penalty1, true);
                if (!penalty1Service.saveOrUpdate(penalty1)) {
                    return Result.error1(false);
                }
            }
        }else{
            return Result.error(false,"存在重复数据");
        }
        return Result.success(flag);
    }

    //根据id删除
    @DeleteMapping("/delete/{id}")  //通过“/user/”+id 的url调用接口
    public Result delete(@PathVariable Integer id) {
        Boolean flag = false;
        flag = penaltyService.removeById(id);
        if (flag){
            if (!penalty1Service.removeById(id)){
                return Result.error1(false);
            }
        }
        return Result.success(flag,"数据删除成功");
    }
    //批量删除
    @PostMapping("/delete/batch")
    public Boolean deleteBatch(@RequestBody List<Integer> ids){
        return penaltyService.removeByIds(ids);
    }

    //查询所有
    @GetMapping("/select/all")
    public Result findAll() {
        List<Penalty> penaltys = penaltyService.list();
        return Result.success(penaltys);
    }

    //根据id查询
    @GetMapping("select/{id}")
    public Result findOne(@PathVariable Integer id) {
        Penalty penalty = penaltyService.getById(id);
        return Result.success(penalty);
    }

    //分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(defaultValue = "") String penaltyids,//defaultValue = ""设置默认值为空
                                    @RequestParam(defaultValue = "") String penaltyname) {

        Page<Penalty> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Penalty> querWrapper = new QueryWrapper<Penalty>();
        if (!"".equals(penaltyids)){
        querWrapper.like("penaltyids",penaltyids);//默认用and连接
        }
        if (!"".equals(penaltyname)){
        querWrapper.like("penaltyname",penaltyname);//或连接为querWrapper.or().like
        }
        IPage<Penalty> penaltyIPage = penaltyService.page(page,querWrapper);
        return Result.success(penaltyIPage);
    }

    //导出excel表格
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        //从数据库查出所以数据
        List<Penalty> list = penaltyService.list();

        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);//也可写为磁盘路径

        //自定义标题别名
        writer.addHeaderAlias("id", "行政处罚信息id");
        writer.addHeaderAlias("penaltyids", "统一社会信用代码");
        writer.addHeaderAlias("penaltyname", "单位名称");
        writer.addHeaderAlias("penaltyauthority", "处罚机关");
        writer.addHeaderAlias("penaltytime", "处罚时间");
        writer.addHeaderAlias("penaltypeople", "负责人");
        writer.addHeaderAlias("penaltyfact", "主要违法事实");
        writer.addHeaderAlias("penaltycontent", "处罚内容");
        writer.addHeaderAlias("penaltyway", "履行方式");

        writer.setColumnWidth(0,10);//0为第一列，列宽
        writer.setColumnWidth(1,25);//0为第一列，列宽
        writer.setColumnWidth(2,25);//0为第一列，列宽
        writer.setColumnWidth(3,25);
        writer.setColumnWidth(4,25);
        writer.setColumnWidth(5,25);
        writer.setColumnWidth(6,40);
        writer.setColumnWidth(7,25);
        writer.setColumnWidth(8,25);

        //设置所有单元格超过设置列间距自动换行
        StyleSet ss = writer.getStyleSet();
        ss.setWrapText();
        writer.setStyleSet(ss);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("行政处罚信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();//将数据刷新到输出流里面
        writer.flush(out, true);
        out.close();
        writer.close();
        }

    //excel表格导入数据
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {  //传入的属性名为file
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);//指定从第二行开始读
        List<Penalty> penaltys = CollUtil.newArrayList();

        List<Penalty1> penalty1s = CollUtil.newArrayList();

        for (List<Object> row : list) {
            Penalty penalty = new  Penalty();
    //            basic.setId(Integer.parseInt (row.get(0).toString())); //id为自增，无需导入
            penalty.setPenaltyids(row.get(0).toString());
            String key = row.get(0).toString();
            int a = getInfo(key);
            if (a != 1){
                continue;
            }
            penalty.setPenaltyname(row.get(1).toString());
            penalty.setPenaltyauthority(row.get(2).toString());
            penalty.setPenaltytime(row.get(3).toString());
            penalty.setPenaltypeople(row.get(4).toString());
            penalty.setPenaltyfact(row.get(5).toString());
            penalty.setPenaltycontent(row.get(6).toString());
            penalty.setPenaltyway(row.get(7).toString());

            penaltys.add(penalty);
        }


        Boolean flag = penaltyService.saveBatch(penaltys);
        if (flag){
            for (List<Object> row : list) {
                Penalty1 penalty1 = new  Penalty1();
        //            basic.setId(Integer.parseInt (row.get(0).toString())); //id为自增，无需导入
                penalty1.setPenaltyids(row.get(0).toString());
                String key = row.get(0).toString();
                int a = getInfo1(key);
                if (a != 1) {
                    continue;
                }
                penalty1.setPenaltyname(row.get(1).toString());
                penalty1.setPenaltyauthority(row.get(2).toString());
                penalty1.setPenaltytime(row.get(3).toString());
                penalty1.setPenaltypeople(row.get(4).toString());
                penalty1.setPenaltyfact(row.get(5).toString());
                penalty1.setPenaltycontent(row.get(6).toString());
                penalty1.setPenaltyway(row.get(7).toString());
                penalty1s.add(penalty1);
            }
            if(!penalty1Service.saveBatch(penalty1s)){
            return Result.error1(false);
            }
        }

        return Result.success(flag,"数据批量导入成功");
        }

    public int getInfo(String key) {  //查询出一条数据
        QueryWrapper<Penalty> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("penaltyids", key);
        int a = 2;
        Penalty one = new Penalty();
        try {
        one = penaltyService.getOne(queryWrapper); // 从数据库查询信息
        } catch (Exception e) {
        a = 3;
        }
        if (one == null){
        a = 1;
        }
        return a; //1为不存在数据
        //2为存在一条数据
        //3为存在多条数据
        }

    //备用数据库查询
    public int getInfo1(String key) {  //查询出一条数据
        QueryWrapper<Penalty1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("penaltyids", key);
        int a = 2;
        Penalty1 one = new Penalty1();
        try {
        one = penalty1Service.getOne(queryWrapper); // 从数据库查询信息
        } catch (Exception e) {
        a = 3;
        }
        if (one == null){
        a = 1;
        }
        return a; //1为不存在数据
        //2为存在一条数据
        //3为存在多条数据
        }


    @GetMapping("/downloadPdf")
    public void downloadPDF(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExportPdf(request, response);
    }

    /**
     * 文档排版
     */
    public void ExportPdf(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/pdf");
        //下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=Penalty.pdf");
        //设置中文
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);


        // 创建文件
        Document document = new Document();

        //设置修改器
        PdfWriter.getInstance(document, response.getOutputStream());
//        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(oldPath));
        // 打开文档
        document.open();
        //设置文档标题
        document.addTitle("PDF");
        //设置文档作者
        document.addAuthor("yyd");
        document.addCreationDate();
        //设置关键字
        document.addKeywords("iText");
        document.addLanguage("中文");
        //表头
        PdfPTable title = new PdfPTable(8);

        title.setWidthPercentage(100); // 宽度100%填充
//        title.setSpacingBefore(10f); // 前间距
//        title.setSpacingAfter(10f); // 后间距

        //设置列宽
        float[] columnWidths = {0.8f, 0.5f ,0.5f,0.5f,0.5f,1.4f,0.6f,0.5f};
        title.setWidths(columnWidths);
        PdfPCell cell;

//        title.HorizontalAlignment = 0;
//        title.TotalWidth = 500;//表格总宽度
//        title.LockedWidth = true;//锁定宽度
//        title.FixedHeight = height;
//        title.MinimumHeight = 36;//设置行高

        title.addCell(new Paragraph("统一社会信用代码", FontChinese));
        title.addCell(new Paragraph("单位名称", FontChinese));
        title.addCell(new Paragraph("处罚机关", FontChinese));
        title.addCell(new Paragraph("处罚时间", FontChinese));
        title.addCell(new Paragraph("负责人", FontChinese));
        title.addCell(new Paragraph("主要违法事实", FontChinese));
        title.addCell(new Paragraph("处罚内容", FontChinese));
        title.addCell(new Paragraph("履行方式", FontChinese));


        document.add(title);

        List<Penalty> list = penaltyService.list();
        for (Penalty row : list) {
            //插入数据
            PdfPTable table = new PdfPTable(8);
            table.setWidthPercentage(100); // 宽度100%填充
            //设置列宽
            table.setWidths(columnWidths);
            table.addCell(new Paragraph(row.getPenaltyids(), FontChinese));
            table.addCell(new Paragraph(row.getPenaltyname(), FontChinese));
            table.addCell(new Paragraph(row.getPenaltyauthority(), FontChinese));
            table.addCell(new Paragraph(row.getPenaltytime(), FontChinese));
            table.addCell(new Paragraph(row.getPenaltypeople(), FontChinese));
            table.addCell(new Paragraph(row.getPenaltyfact(), FontChinese));
            table.addCell(new Paragraph(row.getPenaltycontent(), FontChinese));
            table.addCell(new Paragraph(row.getPenaltyway(), FontChinese));


            document.add(table);
        }

        document.close();
    }


}

